* {
  margin: 0;
  padding: 0;
}

li {
  list-style: none;
}

html,
body {
  width: 100%;
  margin: 0;
  background-color: #161622;
  padding-top: env(safe-area-inset-top);
  padding-bottom: env(safe-area-inset-bottom);
  /* 关键修改：基于 --vh 计算最终高度，加 !important 确保优先级 */
  height: calc(var(--vh) - env(safe-area-inset-top) - env(safe-area-inset-bottom)) !important;
}

ul,
ol {
  list-style: none;
}

#app {
  width: 100%;
  height: 100%;
}

.container {
  width: 100%;
  height: 100%;
  /* 若需要滚动，添加 overflow-auto 避免内容溢出 */
  overflow: auto;
}

.fullscreen-tip {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #fff;
  font-size: 0.3733rem;
  background: rgba(0, 0, 0, 0.5);
  padding: 0.2rem 0.4rem;
  border-radius: 0.2rem;
  z-index: 9999;
  pointer-events: none;
}
</style>

<template>
  <div class="container">
    <router-view></router-view>
    <TabBar v-if="shouldShowTabBar"></TabBar>
    <LoginModal></LoginModal>
    <RegisterModal></RegisterModal>
    <ForgotPasswordModal></ForgotPasswordModal>
    <div class="fullscreen-tip" v-if="!isFullScreen && userStore.isLogin">
      点击任意位置进入全屏
    </div>
  </div>
</template>

<script setup>
import { useRoute, watch, onMounted, onUnmounted } from 'vue-router'; // 新增 watch/onUnmounted
import TabBar from './components/common/TabBar.vue';
import LoginModal from './components/login/LoginModal.vue';
import RegisterModal from './components/login/RegisterModal.vue';
import ForgotPasswordModal from './components/login/ForgotPasswordModal.vue';
import { useUserStore } from '@/store/modules/user/user.js'
import { useMessageStore } from '@/store/modules/message/message.js'
import { useFullScreen } from '@/hooks/useFullScreen.js'
import { fetchFanUnreadNum, fetchLikeUnreadNum, fetchCommentUnreadNum, fetchAtUnreadNum, fetchAllMessageUnreadNums } from './hooks/fetchAllMessageUnreadNums'
import { computed } from 'vue';
const socket = inject('socket')
const messageStore = useMessageStore()
const userStore = useUserStore()
const { isFullScreen, requestFullScreen } = useFullScreen()
const route = useRoute();

const excludePaths = [
  '/video',
  '/user/fans',
  '/user/follows',
  '/message/followers',
  '/message/likes',
  '/message/mentions',
  '/message/comments',
  '/search',
  '/contact-picker',
  'ChatWith',
];

const shouldShowTabBar = computed(() => {
  return !excludePaths.some(path => route.path.includes(path));
});

async function handleLoginSuccess(userId) {
  try {
    const res = await fetchAllMessageUnreadNums(userId);
    messageStore.unreadMessages = {
      ...messageStore.unreadMessages,
      ...res
    };
    console.log('登录时初始化未读数量：', messageStore.unreadMessages);
  } catch (err) {
    console.error('初始化未读数量失败：', err);
  }
}

watch(
  () => userStore.isLogin,
  async (isLogin) => {
    if (isLogin && userStore.userInfo?.userId) {
      if (socket.connected) {
        await handleLoginSuccess(userStore.userInfo.userId)
        socket.emit('login', userStore.userInfo.userId);
      } else {
        await handleLoginSuccess(userStore.userInfo.userId)
        socket.connect();
        socket.once('connect', () => {
          socket.emit('login', userStore.userInfo.userId);
        });
      }
    }
  },
  { immediate: true }
)

// 动态更新 --vh 变量（核心函数）
const updateScreenHeightCSSVar = () => {
  const viewportHeight = window.innerHeight;
  document.documentElement.style.setProperty('--vh', `${viewportHeight}px`);
  console.log('更新 --vh：', viewportHeight); // 调试用，可删除
};

onMounted(() => {
  // 1. 初始化 --vh
  updateScreenHeightCSSVar();
  
  // 2. 监听窗口大小变化（全屏/旋转/窗口缩放都会触发）
  window.addEventListener('resize', updateScreenHeightCSSVar);
  
  // 3. 监听全屏状态变化（保险起见，部分浏览器 resize 不触发）
  watch(isFullScreen, updateScreenHeightCSSVar);
  
  // 4. 首次交互进入全屏
  document.addEventListener('touchstart', handleFirstInteraction, { once: true });
  document.addEventListener('click', handleFirstInteraction, { once: true });
  
  // 5. 路由切换时强制全屏
  watch(
    () => route.path,
    () => {
      if (!isFullScreen.value) {
        requestFullScreen();
        // 全屏后强制更新一次 --vh（解决延迟问题）
        setTimeout(updateScreenHeightCSSVar, 100);
      }
    }
  );

  // Socket 监听（原有代码不变）
  socket.on('receivePrivateLetter', (msg) => {
    console.log('收到私信消息:', msg);
    messageStore.addChatMessage(msg)
  })
  socket.on('receiveComment', (msg) => {
    console.log('收到评论消息:', msg);
    fetchCommentUnreadNum(userStore.userInfo.userId).then(res => {
      messageStore.addCommentMessage(res)
    })
  })
  socket.on('receiveTriggerLike', (msg) => {
    console.log('收到点赞消息:', msg);
    fetchLikeUnreadNum(userStore.userInfo.userId).then(res => {
      messageStore.addLikeMessage(res)
    })
  })
  socket.on('receiveTriggerFollow', (msg) => {
    console.log('收到关注消息:', msg);
    fetchFanUnreadNum(userStore.userInfo.userId).then(res => {
      messageStore.addFanMessage(res)
    })
  })
})

const handleFirstInteraction = () => {
  requestFullScreen();
  // 全屏后强制更新 --vh
  setTimeout(updateScreenHeightCSSVar, 100);
  // 移除监听
  document.removeEventListener('touchstart', handleFirstInteraction);
  document.removeEventListener('click', handleFirstInteraction);
};

onUnmounted(() => {
  // 1. 移除 --vh 变量
  document.documentElement.style.removeProperty('--vh');
  // 2. 移除窗口大小监听（关键！避免内存泄漏）
  window.removeEventListener('resize', updateScreenHeightCSSVar);
  // 3. 移除其他监听
  document.removeEventListener('touchstart', handleFirstInteraction);
  document.removeEventListener('click', handleFirstInteraction);
  socket.off('receiveComment')
  socket.off('receiveTriggerLike')
  socket.off('receiveTriggerFollow')
  socket.off('receivePrivateLetter')
})
</script>* {
  margin: 0;
  padding: 0;
}

li {
  list-style: none;
}

html,
body {
  width: 100%;
  margin: 0;
  background-color: #161622;
  padding-top: env(safe-area-inset-top);
  padding-bottom: env(safe-area-inset-bottom);
  /* 关键修改：基于 --vh 计算最终高度，加 !important 确保优先级 */
  height: calc(var(--vh) - env(safe-area-inset-top) - env(safe-area-inset-bottom)) !important;
}

ul,
ol {
  list-style: none;
}

#app {
  width: 100%;
  height: 100%;
}

.container {
  width: 100%;
  height: 100%;
  /* 若需要滚动，添加 overflow-auto 避免内容溢出 */
  overflow: auto;
}

.fullscreen-tip {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #fff;
  font-size: 0.3733rem;
  background: rgba(0, 0, 0, 0.5);
  padding: 0.2rem 0.4rem;
  border-radius: 0.2rem;
  z-index: 9999;
  pointer-events: none;
}
</style>

<template>
  <div class="container">
    <router-view></router-view>
    <TabBar v-if="shouldShowTabBar"></TabBar>
    <LoginModal></LoginModal>
    <RegisterModal></RegisterModal>
    <ForgotPasswordModal></ForgotPasswordModal>
    <div class="fullscreen-tip" v-if="!isFullScreen && userStore.isLogin">
      点击任意位置进入全屏
    </div>
  </div>
</template>

<script setup>
import { useRoute, watch, onMounted, onUnmounted } from 'vue-router'; // 新增 watch/onUnmounted
import TabBar from './components/common/TabBar.vue';
import LoginModal from './components/login/LoginModal.vue';
import RegisterModal from './components/login/RegisterModal.vue';
import ForgotPasswordModal from './components/login/ForgotPasswordModal.vue';
import { useUserStore } from '@/store/modules/user/user.js'
import { useMessageStore } from '@/store/modules/message/message.js'
import { useFullScreen } from '@/hooks/useFullScreen.js'
import { fetchFanUnreadNum, fetchLikeUnreadNum, fetchCommentUnreadNum, fetchAtUnreadNum, fetchAllMessageUnreadNums } from './hooks/fetchAllMessageUnreadNums'
import { computed } from 'vue';
const socket = inject('socket')
const messageStore = useMessageStore()
const userStore = useUserStore()
const { isFullScreen, requestFullScreen } = useFullScreen()
const route = useRoute();

const excludePaths = [
  '/video',
  '/user/fans',
  '/user/follows',
  '/message/followers',
  '/message/likes',
  '/message/mentions',
  '/message/comments',
  '/search',
  '/contact-picker',
  'ChatWith',
];

const shouldShowTabBar = computed(() => {
  return !excludePaths.some(path => route.path.includes(path));
});

async function handleLoginSuccess(userId) {
  try {
    const res = await fetchAllMessageUnreadNums(userId);
    messageStore.unreadMessages = {
      ...messageStore.unreadMessages,
      ...res
    };
    console.log('登录时初始化未读数量：', messageStore.unreadMessages);
  } catch (err) {
    console.error('初始化未读数量失败：', err);
  }
}

watch(
  () => userStore.isLogin,
  async (isLogin) => {
    if (isLogin && userStore.userInfo?.userId) {
      if (socket.connected) {
        await handleLoginSuccess(userStore.userInfo.userId)
        socket.emit('login', userStore.userInfo.userId);
      } else {
        await handleLoginSuccess(userStore.userInfo.userId)
        socket.connect();
        socket.once('connect', () => {
          socket.emit('login', userStore.userInfo.userId);
        });
      }
    }
  },
  { immediate: true }
)

// 动态更新 --vh 变量（核心函数）
const updateScreenHeightCSSVar = () => {
  const viewportHeight = window.innerHeight;
  document.documentElement.style.setProperty('--vh', `${viewportHeight}px`);
  console.log('更新 --vh：', viewportHeight); // 调试用，可删除
};

onMounted(() => {
  // 1. 初始化 --vh
  updateScreenHeightCSSVar();
  
  // 2. 监听窗口大小变化（全屏/旋转/窗口缩放都会触发）
  window.addEventListener('resize', updateScreenHeightCSSVar);
  
  // 3. 监听全屏状态变化（保险起见，部分浏览器 resize 不触发）
  watch(isFullScreen, updateScreenHeightCSSVar);
  
  // 4. 首次交互进入全屏
  document.addEventListener('touchstart', handleFirstInteraction, { once: true });
  document.addEventListener('click', handleFirstInteraction, { once: true });
  
  // 5. 路由切换时强制全屏
  watch(
    () => route.path,
    () => {
      if (!isFullScreen.value) {
        requestFullScreen();
        // 全屏后强制更新一次 --vh（解决延迟问题）
        setTimeout(updateScreenHeightCSSVar, 100);
      }
    }
  );

  // Socket 监听（原有代码不变）
  socket.on('receivePrivateLetter', (msg) => {
    console.log('收到私信消息:', msg);
    messageStore.addChatMessage(msg)
  })
  socket.on('receiveComment', (msg) => {
    console.log('收到评论消息:', msg);
    fetchCommentUnreadNum(userStore.userInfo.userId).then(res => {
      messageStore.addCommentMessage(res)
    })
  })
  socket.on('receiveTriggerLike', (msg) => {
    console.log('收到点赞消息:', msg);
    fetchLikeUnreadNum(userStore.userInfo.userId).then(res => {
      messageStore.addLikeMessage(res)
    })
  })
  socket.on('receiveTriggerFollow', (msg) => {
    console.log('收到关注消息:', msg);
    fetchFanUnreadNum(userStore.userInfo.userId).then(res => {
      messageStore.addFanMessage(res)
    })
  })
})

const handleFirstInteraction = () => {
  requestFullScreen();
  // 全屏后强制更新 --vh
  setTimeout(updateScreenHeightCSSVar, 100);
  // 移除监听
  document.removeEventListener('touchstart', handleFirstInteraction);
  document.removeEventListener('click', handleFirstInteraction);
};

onUnmounted(() => {
  // 1. 移除 --vh 变量
  document.documentElement.style.removeProperty('--vh');
  // 2. 移除窗口大小监听（关键！避免内存泄漏）
  window.removeEventListener('resize', updateScreenHeightCSSVar);
  // 3. 移除其他监听
  document.removeEventListener('touchstart', handleFirstInteraction);
  document.removeEventListener('click', handleFirstInteraction);
  socket.off('receiveComment')
  socket.off('receiveTriggerLike')
  socket.off('receiveTriggerFollow')
  socket.off('receivePrivateLetter')
})
</script>